//
/**
 * Filename: fig10-5_non_reentrant_func.c
 * Author:   csbonkers
 * Contact:  forever65535@qq.com
 * Date:     2021/6/18
 * Description:
 *    在信号处理函数中调用非可重入函数造成的错误
 */
#include "apue.h"
#include <signal.h>
#include <pwd.h>

static void my_alarm(int signo){
  // 在Linux中，SIGALRM 信号处理器会被系统重置为默认动作
  struct passwd *rootptr; // 重建信号处理器
  signal(SIGALRM, my_alarm);
  printf("in signal handler\n");
  if((rootptr = getpwnam("root")) == NULL){
    err_sys("getpwnam(root) error");
  }
  alarm(1);
}

int main(int argc, char *argv[]) {

  struct passwd *ptr;
  signal(SIGALRM, my_alarm);
  alarm(1);
  for(;;){
    if((ptr = getpwnam("laizili")) == NULL){
      err_sys("getpwnam error");
    }
    if(strcmp(ptr->pw_name, "laizili")!=0){
      printf("return value corrupted!, pw_name = %s\n", ptr->pw_name);
    }
  }
}